const express = require("express");
const apiRouter = express.Router();
// const htmlToDocx = require('html-to-docx');
const path = require("path");
const filePath = path.join(__dirname, "../uploads/");
const fs = require("fs");

// 确保uploads目录存在
if (!fs.existsSync(filePath)) {
    fs.mkdirSync(filePath, { recursive: true });
}

// function exportHtmlToWord(htmlContent) {
//     return new Promise(async (resolve, reject) => {
//         try {
//             const wordBuffer = await htmlToDocx(htmlContent, null, {
//                 margin: { top: 1.5, right: 1.5, bottom: 1.5, left: 1.5 },
//                 orientation: 'portrait',
//                 font: { name: '微软雅黑', size: 14 }
//             });

//             const wordPath = filePath + '/word.docx';
//             await fs.promises.writeFile(wordPath, wordBuffer);

//             resolve({
//                 code: 20000,
//                 msg: '操作成功'
//             })
//         } catch (error) {
//             resolve({
//                 code: 50000,
//                 msg: '操作失败' + error
//             })
//         }
//     })
// }

// 获取所有用户列表
apiRouter.post("/getWord", async (req, res) => {
    const params = req.body;
    let result = await exportHtmlToWord(params.htmlStr);
    if (result.code == 20000) {
        const filePath1 = path.join(filePath, 'word.docx');
        let contentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
        // 设置响应头
        res.type(contentType);
        // 如果需要提示用户下载文件，可以添加 Content-Disposition 头部
        res.setHeader(
            "Content-Disposition",
            `attachment; filename*=utf-8''123.docx`
        );

        // 创建可读流并返回给客户端
        const readStream = fs.createReadStream(filePath1);

        readStream.on("error", (error) => {
            console.error("文件读取错误:", error);
            res.status(500).send({ code: 50000, msg: "文件读取失败" });
        });

        // 将可读流的内容发送到响应中
        readStream.pipe(res);
    }
});

module.exports = apiRouter;
